import React, { useState, useEffect } from 'react';
import { View, Text, FlatList, TouchableOpacity, StyleSheet, Alert, Modal, TouchableWithoutFeedback } from 'react-native';
import { useNavigation } from '@react-navigation/native';
import { get, post } from '../http/http';
import { SegmentedBar } from 'teaset';
const ReviewScreen = () => {
  const [show, setShow] = useState(false);
  const [actions] = useState([
    { name: '审核', value: 0, color: '#4EB894' },
    { name: '驳回', value: 1, color: '#ff8c33' },
  ]);
  const [tabs] = useState([
    { name: '全部', value: '0,10,20,30,80' },
    { name: '待审核', value: '0' },
    { name: '审核通过', value: '10' },
    { name: '进行中', value: '20' },
    { name: '已完成', value: '30' },
    { name: '已驳回', value: '80' },
  ]);
  const [status, setStatus] = useState('loadmore');
  const [list, setList] = useState([]);
  const [page, setPage] = useState(1);
  const [pages, setPages] = useState(1);
  const [orderState, setOrderState] = useState('0');
  const [activeIndex, setActiveIndex] = useState(0);
  const navigation = useNavigation();

  useEffect(() => {
    loadData();
  }, [page, orderState]);

  const loadData = async () => {
    try {
      const response = await get('/stadium/laboratoryOrder/api/queryLaboratoryOrderList?route=stadium', {
        page, limit: 20, orderState,
      });
      const data = response.data;
      setList(prevList => [...prevList, ...data.data]);
      setPages(data.pages);
      setStatus(page >= data.pages ? 'nomore' : 'loading');
    } catch (error) {
      Alert.alert('Error', error.message);
    }
  };

  const click = (index: number) => {
    const item = tabs[index];
    setActiveIndex(index);
    setPage(1);
    setPages(1);
    setStatus('loading');
    setList([]);
    setOrderState(item.value);
  };

  const reserveState = (item) => {
    switch (item.orderState) {
      case 10: return '审核通过';
      case 20: return '进行中';
      case 30: return '已完成';
      case 60: return '用户取消';
      case 70: return '系统取消';
      case 80: return '已驳回';
      default: return '待审核';
    }
  };

  const borderClass = (item) => {
    switch (item.orderState) {
      case 10:
      case 30: return styles.passBorder;
      case 80: return styles.blockBorder;
      default: return styles.reviewBorder;
    }
  };

  const textClass = (item) => {
    switch (item.orderState) {
      case 10:
      case 30: return styles.passText;
      case 80: return styles.blockText;
      default: return styles.reviewText;
    }
  };

  const reserveType = (item) => {
    if (item.isClassroomAppointment === 1 && item.roomType === 0) { return '整间预约'; }
    if (item.isPositionAppointment === 1 && item.roomType === 0) { return '位置预约'; }
    if (item.roomType === 1) { return '朗读亭预约'; }
    return '';
  };

  const selectClick = async (e) => {
    try {
      await post('/stadium/laboratoryOrder/api/checkLaboratoryOrder', {
        orderId: show.orderItem,
        checkState: e.value,
      });
      setShow(false);
      loadData();
    } catch (error) {
      Alert.alert('Error', error.message);
    }
  };

  const showItem = (item) => {
    if (item.orderState === 0) {
      setShow(item);
    }
  };

  return (
    <View style={styles.container}>
      {/* <FlatList
        data={tabs}
        horizontal
        renderItem={({ item }) => (
          <TouchableOpacity onPress={() => click(item)} style={styles.tab}>
            <Text style={styles.tabText}>{item.name}</Text>
          </TouchableOpacity>
        )}
        keyExtractor={(item) => item.value}
      /> */}
      <SegmentedBar
        justifyItem={'fixed'}
        indicatorType={'boxWidth'}
        indicatorPosition={'bottom'}
        indicatorLineColor={'#5cb85c'}
        indicatorLineWidth={1}
        indicatorPositionPadding={3}
        animated={true}
        activeIndex={activeIndex}
        onChange={index => click(index)}
      >
        {tabs.map((item, index) => <SegmentedBar.Item key={'item' + index} title={item.name} />)}
      </SegmentedBar>
      <View style={styles.listContainer}>
        {list.length > 0 ? (
          <FlatList
            data={list}
            renderItem={({ item }) => (
              <TouchableOpacity
                style={[styles.item, borderClass(item)]}
                onPress={() => showItem(item)}
              >
                <View style={styles.itemText}>
                  <Text style={[styles.text, textClass(item)]}>预约人</Text>
                  <Text style={styles.text}>{item.userName}</Text>
                </View>
                <View style={styles.itemText}>
                  <Text style={[styles.text, textClass(item)]}>预约手机号</Text>
                  <Text style={styles.text}>{item.mobilePhone}</Text>
                </View>
                <View style={styles.itemText}>
                  <Text style={[styles.text, textClass(item)]}>预约类型</Text>
                  <Text style={styles.text}>{reserveType(item)}</Text>
                </View>
                <View style={styles.itemText}>
                  <Text style={[styles.text, textClass(item)]}>预约状态</Text>
                  <Text style={styles.text}>{reserveState(item)}</Text>
                </View>
                <View style={styles.itemText}>
                  <Text style={[styles.text, textClass(item)]}>预约教室</Text>
                  <Text style={styles.text}>{item.roomLocation}</Text>
                </View>
                <View style={styles.itemText}>
                  <Text style={[styles.text, textClass(item)]}>预约时间</Text>
                  <Text style={styles.text}>
                    {(item.appointmentDate || '') + ' ' + (item.startTime || '') + '-' + (item.endTime || '')}
                  </Text>
                </View>
              </TouchableOpacity>
            )}
            keyExtractor={(item, index) => index.toString()}
            onEndReached={() => {
              if (page < pages) {
                setPage(page + 1);
              }
            }}
            onEndReachedThreshold={0.5}
            ListFooterComponent={() => (
              <Text style={styles.status}>{status === 'loading' ? '加载中...' : '没有更多数据了'}</Text>
            )}
          />
        ) : (
          <Text style={styles.empty}>{status === 'loading' ? '加载中...' : '没有更多数据了'}</Text>
        )}
      </View>
      <Modal
        animationType="fade"
        transparent
        hardwareAccelerated
        visible={!!show}
      >
        <TouchableWithoutFeedback onPress={() => setShow(false)}>
          <View style={styles.modalBackground}>
            <View style={styles.actionSheet}>
              <Text style={styles.actionSheetTitle}>请选择操作</Text>
              {actions.map((action) => (
                <TouchableOpacity
                  key={action.value}
                  onPress={() => selectClick(action)}
                  style={[styles.actionSheetItem, { color: action.color }]}
                >
                  <Text style={{ color: action.color }}>{action.name}</Text>
                </TouchableOpacity>
              ))}
              <TouchableOpacity onPress={() => setShow(false)} style={styles.actionSheetCancel}>
                <Text>取消</Text>
              </TouchableOpacity>
            </View>
          </View>
        </TouchableWithoutFeedback>
      </Modal>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#F7F8F8',
  },
  tab: {
    padding: 10,
    borderBottomWidth: 2,
    borderBottomColor: '#4EB894',
  },
  tabText: {
    color: '#4EB894',
    fontWeight: 'bold',
  },
  listContainer: {
    flex: 1,
    borderTopColor: '#999',
    borderTopWidth: 1,
    marginTop: -4,
  },
  item: {
    backgroundColor: 'white',
    boxShadow: '0px 0px 3px 1px rgba(0, 0, 0, 0.08)',
    margin: 15,
    borderLeftWidth: 6,
    borderRadius: 15,
    color: '#424242',
    padding: 10,
  },
  itemText: {
    flexDirection: 'row',
    alignItems: 'center',
    padding: 10,
  },
  text: {
    flex: 1,
    fontSize: 14,
  },
  passText: {
    color: '#4EB894',
    fontWeight: 'bold',
  },
  blockText: {
    color: '#ff8c33',
    fontWeight: 'bold',
  },
  reviewText: {
    color: '#ffc800',
    fontWeight: 'bold',
  },
  passBorder: {
    borderLeftColor: '#4EB894',
  },
  blockBorder: {
    borderLeftColor: '#ff8c33',
  },
  reviewBorder: {
    borderLeftColor: '#ffc800',
  },
  status: {
    textAlign: 'center',
    color: '#4EB894',
    marginVertical: 10,
  },
  empty: {
    textAlign: 'center',
    color: '#4EB894',
    marginVertical: 20,
  },
  actionSheet: {
    position: 'absolute',
    bottom: 0,
    left: 0,
    right: 0,
    backgroundColor: 'white',
    padding: 20,
    borderTopLeftRadius: 10,
    borderTopRightRadius: 10,
    boxShadow: '0px -2px 10px rgba(0, 0, 0, 0.1)',
  },
  modalBackground: {
    flex: 1,
    backgroundColor: 'rgba(0, 0, 0, 0.5)', // 半透明黑色背景

  },
  actionSheetTitle: {
    fontSize: 18,
    fontWeight: 'bold',
    marginBottom: 10,
  },
  actionSheetItem: {
    padding: 15,
    borderBottomWidth: 1,
    borderBottomColor: '#eee',
  },
  actionSheetCancel: {
    padding: 15,
    alignItems: 'center',
  },
});

export default ReviewScreen;
